<template>
  <div class="customer-page">
    <div class="customer-edit">
      <p class="edit-title">{{ this.select.name}}</p>
      <p class="edit-conter">
        <span class="edit_phonecode van-hairline--bottom"
          @click="seclectCode" v-if="type === 'phone'">
          <strong>{{ phoneCode }}</strong>
          <svg aria-hidden="true" class="edit_icon">
            <use xlink:href="#icon-xialajiantou"></use>
          </svg>
        </span>
        <material-input
          :placeholder="`请输入${this.select.name}`"
          :type="this.select.inputType"
          :maxlength="this.select.maxlength"
          v-model="inputValue"
          @input="inputHandler"
        >
          <span v-if="this.select.inputType === 'textarea'">
            {{ this.select.maxlength - inputValue.length }}
          </span>
        </material-input>
      </p>
      <button class="edit-query" @click="saveInfo" :disabled="disable">保存</button>
      <van-actionsheet
        v-model="show"
        :actions="actions"
        cancel-text="取消"
        @select="onSelect"
        @cancel="onCancel"
      />
    </div>
  </div>
</template>
<script>
import MaterialInput from 'COMP/MaterialInput'
import CustomService from 'SERVICE/customService'
import strFormat from '@/filters/strFormat'

const typeList = {
  remarkName: {
    name:  '备注名称',
    inputType: "text",
    maxlength: 15
  },
  intentionDescription: {
    name:  '其它描述',
    inputType: "textarea",
    maxlength: 120
  },
  phone: {
    name:  '手机号',
    inputType: "tel",
    maxlength: 11
  },
}

export default {
  data () {
    return {
      type: '', // 编辑字段
      label: '', // 编辑文本展示
      clientId: '',
      inputValue: '',
      typeList,
      phoneCode: '',
      show: false,
      select: {},
      actions: [
        { name: '中国大陆 +86', phoneCode: '+86' },
        { name: '香港 +852', phoneCode: '+852' },
      ],
      disable: true,
    }
  },
  created () {
    let { areaCode, type, clientId } = this.$route.query
    this.phoneCode = areaCode || "+86"
    this.type = type || 'remarkName'
    this.clientId = clientId || this.$route.params.id
    this.inputValue = this.$route.query[type]
    // this.label = this.inputValue ? "编辑" : "添加"
    this.select = this.typeList[type] || {}
    document.title = "设置" + this.select.name
  },
  watch: {
    inputValue (newValue, oldValue) {
      if (newValue == '') {
        this.disable = true;
      } else {
        this.disable = false;
      }
    }
  },
  methods: {
    onSelect (item) {
      this.phoneCode = item.phoneCode;
      this.inputValue = '';
      this.show = false;
    },
    onCancel () {
      this.show = false;
    },
    seclectCode () {
      this.show = true;
    },
    /**
     * 过滤特殊字符
     */
    inputHandler () {
      let type = this.type
      let inputStr = type === 'phone' ? this.inputValue.replace(/[^0-9]/ig, "") : strFormat.fmtStrStan(this.inputValue)
      if (this.type === 'remarkName') {
        this.getSubStr(inputStr)
      } else {
        // setTimeout(() => {
        this.inputValue = inputStr
        // }, 0);
      }
    },
    /**
     * 字符截取
     */
    getSubStr (str) {
      let len = strFormat.getLen(str)
      if (len >= 30) {
        let tempLen = 0
        let index = 0
        for (let i = 0; i < str.length; i++) {
          tempLen += strFormat.getLen(str[i])
          if (tempLen >= 30) {
            index = i
            break
          }
        }
        setTimeout(() => {
          this.inputValue = str.slice(0, index + 1)
        }, 1);
      }
    },
    /**
     * 保存信息
     */
    saveInfo () {
      let inputValue = this.inputValue
      let type = this.type
      let message = ''
      if (!inputValue) {
        message = `${this.label}不可为空`
      }
      if (!message && type === 'phone' && !(/^1\d{10}$/.test(inputValue)) && this.phoneCode === '+86') {
        message = `请输入正确的手机号码`
      } else if ( !message && type === 'phone' && inputValue.length !== 8 && this.phoneCode === '+852') {
        message = `请输入正确的手机号码`
      }

      if (message) {
        this.$dialog.alert({
          message: message
        }).then(() => { })
        return false
      }
      
      let params = {
        clientId: this.clientId,
        [this.type]: this.inputValue,
      }
      if (this.type === "phone") {
        params.areaCode = this.phoneCode
      }
      this.updateInfo(params)
    },
    /**
     * 更新信息和缓存信息
     */
    async updateInfo (params) {
      try {
        await CustomService.updateCustomerInfo(params)
        sessionStorage.removeItem("listInfo")
        // let zipData = sessionStorage.getItem("listInfo")
        // if (zipData && !params.intentionDescription) {
        //   let query = {
        //     "phone": "clientMobile",
        //     "remarkName" : "clientRemarkName",
        //     // "intentionDescription" : "intentionDescription"
        //   }
        //   let cacheData = JSON.parse(zipData)
        //   if (cacheData.listInfo && cacheData.listInfo.length) {
        //     cacheData.listInfo.forEach(item => {
        //       if (item.clientId === this.clientId) {
        //         let value = query[this.type]
        //         if (item[value]) {
        //           item[value] = params[this.type]
        //         } else {
        //           item['clientName'] = params[this.type]
        //         }
        //       }
        //     })
        //   }
        //   let changeData = JSON.stringify(cacheData)
        //   sessionStorage.setItem("listInfo", changeData)
        // }
        this.$toast({
          type: 'success',
          duration: 1000,
          message: '保存成功'
        })
        setTimeout(() => {
          this.$router.go(-1)
        }, 1000)
      } catch (error) {
        console.log(error)
      }
    }
  },
  components: {
    MaterialInput
  }
}
</script>

<style lang="less" scoped>
.material-input__component {
  flex: 1;
  margin-top: 0;
  // overflow: hidden;
  font-size: 0;
  /deep/ .material-label {
    position: absolute;
    bottom: 6px;
    right: 6px;
    left: inherit;
    top: inherit;
    color: #9BA4B4;
    font-size: 12px;
  }
}

.customer-page {
  background: #ffffff;
  padding: 30px 15px;
  box-sizing: border-box;
  > .customer-edit {
    > .edit-title {
      font-size: 24px;
      font-weight: 600;
      color: #13284D;
      line-height: 32px;
      margin-bottom: 22px;
    }
    > .edit-conter {
      display: flex;
      .edit_phonecode {
        width: 20%;
        color: #13284D;
        font-size: 16px;
        align-items: center;
        display: flex;
        .edit_icon {
          width: 16px;
          height: 16px;
          margin-left: 5px;
        }
      }
      > .edit-input {
        font-size: 15px;
        font-weight: 500;
        color: rgba(153, 153, 153, 1);
        height: 21px;
        line-height: 21px;
        width: 99%;
        border: 0;
        border-bottom: 1px solid #eee;
      }
    }

    > .edit-query {
      font-size: 16px;
      font-weight: 400;
      color: #fff;
      line-height: 22px;
      height: 44px;
      background: #007AE6;
      border-radius: 4px;
      width: 100%;
      border: 0;
      margin-top: 48px;
    }
    button[disabled] {
      opacity: 0.5;
    }
  }
}
</style>
